package com.algorithm.example.queue.blockingQueue;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 单锁实现
 * </p>
 *
 * @author lzt
 * @version 1.0
 * @since 2024/1/28 20:11
 */
public class BlockingQueue1<E> implements BlockingQueue<E> {

    private final E[] array;
    private int head;
    private int tail;
    private int size;
    private ReentrantLock lock = new ReentrantLock();
    private Condition headWaits = lock.newCondition();
    private Condition tailWaits = lock.newCondition();

    public BlockingQueue1(int capacity) {
        this.array = (E[]) new Object[capacity];
    }

    @Override
    public void offer(E e) throws InterruptedException {
        // 加锁
        lock.lockInterruptibly();
        try {
            while (isFull()) {
                // 等待唤醒
                tailWaits.await();
            }
            array[tail] = e;
            if(++tail >= array.length){
                tail = 0;
            }
            size++;
            // 唤醒线程
            headWaits.signal();
        } finally {
            // 解锁
            lock.unlock();
        }
    }

    @Override
    public boolean offer(E e, long timeout) throws InterruptedException {
        // 加锁
        lock.lockInterruptibly();
        // 毫秒 -> 纳米
        long t = TimeUnit.MILLISECONDS.toNanos(timeout);
        try {
            while (isFull()) {
                if (t <= 0) {
                    return false;
                }
                // 等待唤醒
                t = tailWaits.awaitNanos(t);
            }
            array[tail] = e;
            if(++tail > array.length){
                tail = 0;
            }
            size++;
            // 唤醒线程
            headWaits.signal();
        } finally {
            // 解锁
            lock.unlock();
        }
        return true;
    }

    @Override
    public E poll() throws InterruptedException {
        lock.lockInterruptibly();
        try {
            while (isEmpty()) {
                headWaits.await();
            }
            E e = array[head];
            array[head] = null;
            if(++head >= array.length) {
                head = 0;
            };
            size--;
            tailWaits.signal();
            return e;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 队列容量是否已满
     *
     * @return 满返回true 否则返回false
     */
    public boolean isFull() {
        return size == array.length;
    }

    /**
     * 队列是否为空
     *
     * @return 空返回true 否则返回false
     */
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        return "BlockingQueue1{" +
                "array=" + Arrays.toString(array) +
                '}';
    }
}
